import { useState, useCallback } from "react";
import "./Login.css";

const Login = () => {
  const [phone, setPhone] = useState("");
  const [password, setPassword] = useState("");
  const [errors, setErrors] = useState({});
  const [isSubmitting, setIsSubmitting] = useState(false);

  // 表单验证
  const validateForm = () => {
    const newErrors = {};

    if (!phone) {
      newErrors.phone = "请输入手机号";
    } else if (!/^1[3-9]\d{9}$/.test(phone)) {
      newErrors.phone = "请输入有效的手机号";
    }

    if (!password) {
      newErrors.password = "请输入密码";
    } else if (password.length < 6) {
      newErrors.password = "密码长度至少6位";
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 处理登录
  const handleSubmit = useCallback(
    async (e) => {
      e.preventDefault();

      if (isSubmitting) return; // 防止重复提交

      if (!validateForm()) return;

      try {
        setIsSubmitting(true);
        // 这里添加实际的登录逻辑
        await new Promise((resolve) => setTimeout(resolve, 1500)); // 模拟登录请求
        alert("登录成功！");
      } catch (error) {
        alert("登录失败，请重试");
      } finally {
        setIsSubmitting(false);
      }
    },
    [phone, password, isSubmitting]
  );

  return (
    <div className="login-container">
      <form className="login-form" onSubmit={handleSubmit}>
        <h2>用户登录</h2>

        <div className="form-group">
          <input
            type="tel"
            value={phone}
            onChange={(e) => setPhone(e.target.value)}
            placeholder="请输入手机号"
            className={errors.phone ? "error" : ""}
          />
          {errors.phone && (
            <span className="error-message">{errors.phone}</span>
          )}
        </div>

        <div className="form-group">
          <input
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="请输入密码"
            className={errors.password ? "error" : ""}
          />
          {errors.password && (
            <span className="error-message">{errors.password}</span>
          )}
        </div>

        <button
          type="submit"
          className={`login-button ${isSubmitting ? "submitting" : ""}`}
          disabled={isSubmitting}
        >
          {isSubmitting ? "登录中..." : "登录"}
        </button>
      </form>
    </div>
  );
};

export default Login;
